package com.zlp.clazz;

import java.io.IOException;
import java.io.InputStream;

public class ClazzLoaderDemo_1 {

    public static void main(String[] args) throws Exception {
       MyClassLoader2 myClassLoader2 = new MyClassLoader2();

        System.out.println(myClassLoader2.getParent());
        Object o = myClassLoader2.loadClass("com.zlp.clazz.Parametric").newInstance();
        System.out.println(o.getClass().getClassLoader());
        System.out.println(o instanceof Parametric);
    }
}
class MyClassLoader2 extends ClassLoader{
    /*
     * 重写loadClass方法违反了双亲委派模型,
     * */
    public Class<?> loadClass(String name) throws ClassNotFoundException {

        try {
            String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
            InputStream is = getClass().getResourceAsStream(fileName);
            if(is == null){
                return super.loadClass(name);
            }
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            return defineClass(name,bytes,0,bytes.length);
        } catch (IOException e) {
            throw new ClassNotFoundException(name);
        }
    }
}
